package cn.itsource.hrm.config;

import cn.itsource.hrm.userdetails.HrmUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity //开启web安全配置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    //已经定义了自己UserDetailSErvice
    @Bean
    public UserDetailsService userDetailsService(){
        return new HrmUserDetailsService();
    }
    //密码编码器：不加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //授权规则配置
    @Override //http安全配置
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()                               //授权配置
                .antMatchers("/login").permitAll()  //登录路径放行
                .antMatchers("/login.html").permitAll()//登录页面放行
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
                .successForwardUrl("/loginSuccess")             // 设置登陆成功页
                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨域伪造检查

    }


    /**
     * 从新实例化bean
     */
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}